﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace ConsoleGifAnimator
{
    internal class Program
    {
        private static void Main()
        {
            const string sourceFolder = @"C:\eclipse\Projects\ConsoleGifAnimator\Frames";
            const string path = @"C:\eclipse\Projects\ConsoleGifAnimator\result1.gif";

            string[] files = Directory.GetFiles(sourceFolder, "*.bmp");
            var bitmaps = new List<Bitmap>(files.Length);

            foreach (string file in files)
            {
                bitmaps.Add((Bitmap)Bitmap.FromFile(file));
            }
            
            Stopwatch sw = new Stopwatch();

            sw.Start();

            // Define the image palette
            //BitmapPalette myPalette = BitmapPalettes.Gray16;

            var gEnc = new GifBitmapEncoder();
            
            foreach (Bitmap bmpImage in bitmaps)
            {
                //int stride = bmpImage.Width / 8;
                //byte[] pixels = new byte[bmpImage.Height * stride];

                //BitmapSource src = BitmapSource.Create(bmpImage.Width, bmpImage.Height, 96, 96,
                //    PixelFormats.Indexed1, myPalette, pixels, stride);

                BitmapSource src = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    bmpImage.GetHbitmap(),
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());

                

                var frame = BitmapFrame.Create(src);
                gEnc.Frames.Add(frame);
            }

            sw.Stop();

            gEnc.Save(new FileStream(path, FileMode.Create));

            Console.WriteLine("Time: {0}ms", sw.ElapsedMilliseconds);
            Console.WriteLine("Press any key");
            Console.ReadKey();
        }
    }
}